<template>
  <svg class="connection" :style="connectionStyle">
    <path :d="pathData" :stroke="connection.selected ? '#4299e1' : '#718096'" :class="connection.selected ? 'line-selected' : 'line-normal'"
      :stroke-width="connection.selected ? 3 : 2" fill="none" @mousedown.stop="handleMouseDown" />
  </svg>
</template>

<script>
export default {
  name: 'Connection',
  props: {
    connection: {
      type: Object,
      required: true
    },
    sourceNode: {
      type: Object,
      required: true
    },
    targetNode: {
      type: Object,
      required: true
    }
  },
  inject: {
    scale: {
      from: 'scale',
      default: () => 1
    },
    translateX: {
      from: 'translateX',
      default: () => 0
    },
    translateY: {
      from: 'translateY',
      default: () => 0
    }
  },
  computed: {
    startPoint() {
      
      // 使用源节点的输出端点绝对坐标
      if (this.sourceNode && this.sourceNode.outputs && 
          this.sourceNode.outputs[this.connection.sourcePortIndex]) {
            
        return this.sourceNode.outputs[this.connection.sourcePortIndex];
      }
      // 兼容处理：如果没有计算好的坐标，则使用原来的计算方式
      const port = this.sourceNode.outputs[this.connection.sourcePortIndex];
      return {
        x: this.sourceNode.x + port.x,
        y: this.sourceNode.y + port.y
      };
    },
    endPoint() {
      // 使用目标节点的输入端点绝对坐标
      if (this.targetNode && this.targetNode.inputs && 
          this.targetNode.inputs[this.connection.targetPortIndex]) {
        return this.targetNode.inputs[this.connection.targetPortIndex];
      }
      // 兼容处理：如果没有计算好的坐标，则使用原来的计算方式
      const port = this.targetNode.inputs[this.connection.targetPortIndex];
      return {
        x: this.targetNode.x + port.x,
        y: this.targetNode.y + port.y
      };
    },
    pathData() {
  
      if (!this.sourceNode || !this.targetNode) {
        return '';
      }
      console.log(this.startPoint)
      console.log(this.endPoint)
      const { x: startX, y: startY } = this.startPoint;
      const { x: endX, y: endY } = this.endPoint;
      // return `M ${startX} ${startY} C ${startX + 100} ${startY}, ${endX - 100} ${endY}, ${endX} ${endY}`;
      const midX = (startX + endX) / 2;
      return `M${startX},${startY} C${midX},${startY} ${midX},${endY} ${endX},${endY}`;
    },
    connectionStyle() {
      return {
        position: 'absolute',
        top: 0,
        left: 0,
        width: '100%',
        height: '100%',
        zIndex: 1
      };
    }
  },
  methods: {
    handleMouseDown() {
      this.$emit('select', this.connection);
    }
  }
};
</script>

<style>
@import '../assets/styles/connection.css';
</style>